package com.sijibao.amap.frg;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.drawable.ColorDrawable;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMap.InfoWindowAdapter;
import com.amap.api.maps.AMap.OnCameraChangeListener;
import com.amap.api.maps.AMap.OnInfoWindowClickListener;
import com.amap.api.maps.AMap.OnMapClickListener;
import com.amap.api.maps.AMap.OnMapLoadedListener;
import com.amap.api.maps.AMap.OnMarkerClickListener;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.MapsInitializer;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.GeocodeSearch.OnGeocodeSearchListener;
import com.amap.api.services.geocoder.RegeocodeAddress;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.amap.api.services.poisearch.PoiItemDetail;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.amap.api.services.poisearch.PoiSearch.OnPoiSearchListener;
import com.amap.api.services.poisearch.PoiSearch.SearchBound;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DrivePath;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.RouteSearch.DriveRouteQuery;
import com.amap.api.services.route.RouteSearch.OnRouteSearchListener;
import com.amap.api.services.route.WalkRouteResult;
import com.android.volley.toolbox.ImageLoader;
import com.makeramen.RoundedImageView;
import com.sijibao.amap.OffLineMapUtils;
import com.sijibao.amap.R;
import com.sijibao.amap.frg.ChoiceNaviPopView.ClosePopEvent;
import com.sijibao.amap.route.DrivingRouteOverlay;
import com.squareup.otto.Subscribe;
import com.yicai.net.Rop;
import com.yicai.sijibao.utl.BusProvider;
import com.yicai.sijibao.utl.DimenTool;
import com.yicai.volley.BaseVolley;

public class AMapFrg extends Fragment implements OnMarkerClickListener,
		OnMapClickListener, OnInfoWindowClickListener, InfoWindowAdapter,
		OnPoiSearchListener, OnRouteSearchListener, OnCameraChangeListener,
		LocationSource, AMapLocationListener {

	private PoiSearch.Query query;
	private OnLocationChangedListener mListener;
	private LocationManagerProxy aMapManager;
	private PoiSearch poiSearch;
	private PoiResult poiResult;
	private int currentPage = 0;// 当前页面，从0开始计数
	private int type;
	private double centerLat;
	private double centerLon;
	private double myLat;
	private double myLon;

	public static AMapFrg buildRoute(double startLat, double startLon,
			double endLat, double endLon) {

		AMapFrg frg = new AMapFrg();
		Bundle bundle = new Bundle();
		bundle.putDouble("startLon", startLon);
		bundle.putDouble("startLat", startLat);
		bundle.putDouble("endLon", endLon);
		bundle.putDouble("endLat", endLat);
		bundle.putInt("type", 1);
		frg.setArguments(bundle);
		return frg;
	}

	/**
	 * 需要定位lat 和 lon 传0.0
	 * 
	 * @param queryType
	 *            "餐饮|4s|酒店"
	 * @param icon
	 *            地图中间点的图标
	 * @param lat
	 *            必传
	 * @param lon
	 *            必传 lon lat 都传0.0则自己去定位
	 * @return
	 */
	public static AMapFrg buildSelectPoint(String queryType, int icon,
			double lat, double lon) {
		AMapFrg frg = new AMapFrg();
		Bundle bundle = new Bundle();
		bundle.putString("queryType", queryType);
		bundle.putInt("type", 2);
		bundle.putInt("icon", icon);
		bundle.putDouble("lat", lat);
		bundle.putDouble("lon", lon);
		frg.setArguments(bundle);
		return frg;
	}
	/**
	 * 查询地理位置
	 * 
	 * type = 11
	 * @param queryType
	 *            "餐饮|4s|酒店"
	 * @return
	 */
	public static AMapFrg buildGeocoderSearch(String queryType,double lat, double lon) {
		AMapFrg frg = new AMapFrg();
		Bundle bundle = new Bundle();
		bundle.putInt("type", 11);
		bundle.putString("queryType", queryType);
		bundle.putDouble("lat", lat);
		bundle.putDouble("lon", lon);
		frg.setArguments(bundle);
		return frg;
	}

	/**
	 * 
	 * @param content
	 *            描述
	 */
	public static AMapFrg buildPoint(double lat, double lon, String content) {
		AMapFrg frg = new AMapFrg();
		Bundle bundle = new Bundle();
		bundle.putDouble("lat", lat);
		bundle.putDouble("lon", lon);
		bundle.putString("content", content);
		bundle.putInt("type", 3);
		frg.setArguments(bundle);
		return frg;
	}

	public static AMapFrg buildNAV(String content, double endLat, double endLon) {
		AMapFrg frg = new AMapFrg();
		Bundle bundle = new Bundle();
		bundle.putDouble("endLon", endLon);
		bundle.putDouble("endLat", endLat);
		bundle.putString("content", content);
		bundle.putInt("type", 4);
		frg.setArguments(bundle);
		return frg;
	}

	public static AMapFrg buildMultiPoint(List<MyLatLon> pointList) {
		AMapFrg frg = new AMapFrg();
		Bundle bundle = new Bundle();
		bundle.putParcelableArrayList("pointList",
				(ArrayList<? extends Parcelable>) pointList);
		bundle.putInt("type", 5);
		frg.setArguments(bundle);
		return frg;
	}

	public static AMapFrg buildTouxiangPoint(double lat, double lon,
			String content, String url) {
		AMapFrg frg = new AMapFrg();
		Bundle bundle = new Bundle();
		bundle.putDouble("lat", lat);
		bundle.putDouble("lon", lon);
		bundle.putString("content", content);
		bundle.putString("url", url);
		bundle.putInt("type", 6);
		frg.setArguments(bundle);
		return frg;
	}

	public static AMapFrg buildSelectPoint2(String queryType, int icon,
			double lat, double lon, String url) {
		AMapFrg frg = new AMapFrg();
		Bundle bundle = new Bundle();
		bundle.putString("queryType", queryType);
		bundle.putInt("type", 7);
		bundle.putInt("icon", icon);
		bundle.putDouble("lat", lat);
		bundle.putDouble("lon", lon);
		bundle.putString("url", url);
		frg.setArguments(bundle);
		return frg;
	}

	public static AMapFrg buildNAVMoreContent(String[] contentArray,
			double endLat, double endLon) {
		AMapFrg frg = new AMapFrg();
		Bundle bundle = new Bundle();
		bundle.putDouble("endLon", endLon);
		bundle.putDouble("endLat", endLat);
		bundle.putStringArray("contentArray", contentArray);
		bundle.putInt("type", 8);
		frg.setArguments(bundle);
		return frg;
	}

	public static AMapFrg buildNAVMoreContentCarOrDriver(String[] contentArray,
			double endLat, double endLon) {
		AMapFrg frg = new AMapFrg();
		Bundle bundle = new Bundle();
		bundle.putDouble("endLon", endLon);
		bundle.putDouble("endLat", endLat);
		bundle.putStringArray("contentArray", contentArray);
		bundle.putInt("type", 9);
		frg.setArguments(bundle);
		return frg;
	}

	public static AMapFrg buildNAVCarOrDriver(String content, double endLat,
			double endLon) {
		AMapFrg frg = new AMapFrg();
		Bundle bundle = new Bundle();
		bundle.putDouble("endLon", endLon);
		bundle.putDouble("endLat", endLat);
		bundle.putString("content", content);
		bundle.putInt("type", 10);
		frg.setArguments(bundle);
		return frg;
	}

	private AMap aMap;
	private MapView mapView;

	private Marker startMk, targetMk;
	private LatLonPoint startPoint = null;
	private LatLonPoint endPoint = null;
	private RouteSearch routeSearch;

	private DriveRouteResult driveRouteResult;// 驾车模式查询结果

	private double navEndLat;
	private double navEndLon;

	private PopupWindow pop;

	private RelativeLayout dingweiRL;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view = inflater.inflate(R.layout.frg_amap, null);
		MapsInitializer.sdcardDir = OffLineMapUtils
				.getSdCacheDir(getActivity());
		mapView = (MapView) view.findViewById(R.id.map);
		dingweiRL = (RelativeLayout) view.findViewById(R.id.dingweiRL);
		dingweiRL.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (aMapManager == null) {
					aMapManager = LocationManagerProxy
							.getInstance(getActivity());
				}
				aMapManager.requestLocationData(
						LocationProviderProxy.AMapNetwork, -1, 100,
						AMapFrg.this);
			}
		});
		mapView.onCreate(savedInstanceState);// 此方法必须重写
		init();
		return view;
	}

	@Subscribe
	public void moveToPointEvent(MoveToSelectedPointEvent event) {
		LatLng point1 = new LatLng(event.lat, event.lon);
		aMap.moveCamera(CameraUpdateFactory.changeLatLng(point1));
	}

	public static class MoveToSelectedPointEvent {
		public double lat;
		public double lon;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onViewCreated(view, savedInstanceState);
		Bundle bundle = getArguments();
		type = bundle.getInt("type");
		if (type == 1) {
			drawRoute(bundle);
		}
		if (type == 2) {
			selectPoi();
		}
		if (type == 3) {
			drawPoint();
		}
		if (type == 4) {
			drawNav();
		}
		if (type == 5) {
			drawMultiPoint();
		}
		if (type == 6) {
			drawTouxiangPoint();
		}
		if (type == 7) {
			selectPoi();
		}
		if (type == 8) {
			drawNav();
		}
		if (type == 9 || type == 10) {
			drawNavCarAndDriver();
		}
		if (type == 11) {			
			selectAddress();
		}
	}

	private void drawPoint() {
		aMap.clear();
		Bundle bundle = getArguments();
		final double lat = bundle.getDouble("lat");
		final double lon = bundle.getDouble("lon");
		String content = bundle.getString("content");
		Marker myMarker = aMap.addMarker(new MarkerOptions().anchor(0.5f, 0.5f)
				.position(new LatLng(lat, lon)).title(content)
				// .icon(BitmapDescriptorFactory.fromResource(R.drawable.start))
				.draggable(true).period(50));
		myMarker.showInfoWindow();
		aMap.setOnMapLoadedListener(new OnMapLoadedListener() {

			@Override
			public void onMapLoaded() {
				// TODO Auto-generated method stub
				LatLng point1 = new LatLng(lat, lon);
				aMap.moveCamera(CameraUpdateFactory.changeLatLng(point1));
				aMap.moveCamera(CameraUpdateFactory.zoomTo(18));
			}
		});
	}

	private void drawTouxiangPoint() {
		aMap.clear();
		aMap.getUiSettings().setZoomControlsEnabled(false);
		Bundle bundle = getArguments();
		final String url = bundle.getString("url");
		final double lat = bundle.getDouble("lat");
		final double lon = bundle.getDouble("lon");
		// String content = bundle.getString("content");
		// TouXiangMarkerView view = new TouXiangMarkerView(getActivity(), url);
		Marker myMarker = aMap.addMarker(new MarkerOptions()
				.anchor(0.5f, 0.5f)
				.position(new LatLng(lat, lon))
				.snippet("头像")
				// .icon(BitmapDescriptorFactory.fromView(view))
				.icon(BitmapDescriptorFactory
						.fromResource(R.drawable.amap_point))
				.draggable(true).period(50));
		myMarker.showInfoWindow();
		aMap.setOnMapLoadedListener(new OnMapLoadedListener() {

			@Override
			public void onMapLoaded() {
				// TODO Auto-generated method stub
				LatLng point1 = new LatLng(lat, lon);
				aMap.moveCamera(CameraUpdateFactory.changeLatLng(point1));
				aMap.moveCamera(CameraUpdateFactory.zoomTo(18));
			}
		});
	}

	private void drawMultiPoint() {
		aMap.clear();
		Bundle bundle = getArguments();
		final List<MyLatLon> pointList = bundle
				.getParcelableArrayList("pointList");
		for (int i = 0; i < pointList.size(); i++) {
			MyLatLon ll = pointList.get(i);
			String content = ll.content;
			double lat = ll.lat;
			double lon = ll.lon;
			Marker myMarker = aMap.addMarker(new MarkerOptions()
					.anchor(0.5f, 0.5f).position(new LatLng(lat, lon))
					.title(content)
					// .icon(BitmapDescriptorFactory.fromResource(R.drawable.start))
					.draggable(true).period(50));
		}
		aMap.setOnMapLoadedListener(new OnMapLoadedListener() {

			@Override
			public void onMapLoaded() {
				// TODO Auto-generated method stub
				if (pointList.size() > 1) {
					LatLngBounds.Builder builder = new LatLngBounds.Builder();
					for (int i = 0; i < pointList.size(); i++) {
						MyLatLon ll = pointList.get(i);
						double lat = ll.lat;
						double lon = ll.lon;
						builder.include(new LatLng(lat, lon));
					}
					aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(
							builder.build(), 20));
				} else if (pointList.size() == 1) {
					MyLatLon ll = pointList.get(0);
					LatLng point1 = new LatLng(ll.lat, ll.lon);
					aMap.moveCamera(CameraUpdateFactory.changeLatLng(point1));
					aMap.moveCamera(CameraUpdateFactory.zoomTo(18));
				}

			}
		});
	}

	private void selectPoi() {
		aMap.setOnCameraChangeListener(this);
		aMap.getUiSettings().setZoomControlsEnabled(false);
		Bundle bundle = getArguments();
		if (bundle.getInt("type") == 2) {
			dingweiRL.setVisibility(View.VISIBLE);
			aMap.setLocationSource(this);// 设置定位监听
			// aMap.getUiSettings().setMyLocationButtonEnabled(true); //
			// 是否显示默认的定位按钮
			// aMap.setMyLocationEnabled(true);// 是否可触发定位并显示定位层
		}

		if (bundle.getDouble("lat") == 0.0 && bundle.getDouble("lon") == 0.0) {
			aMap.setLocationSource(this);// 设置定位监听
			// aMap.getUiSettings().setMyLocationButtonEnabled(true); //
			// 是否显示默认的定位按钮
			// aMap.setMyLocationEnabled(true);// 是否可触发定位并显示定位层
			aMap.setMyLocationStyle(new MyLocationStyle()
					.myLocationIcon(BitmapDescriptorFactory
							.fromResource(getArguments().getInt("icon"))));
			if (aMapManager == null) {
				aMapManager = LocationManagerProxy
						.getInstance(getActivity());
			}
			aMapManager.requestLocationData(
					LocationProviderProxy.AMapNetwork, -1, 100,
					AMapFrg.this);
			aMap.setOnMapLoadedListener(new OnMapLoadedListener() {

				@Override
				public void onMapLoaded() {
					// TODO Auto-generated method stub
					// LatLng point1 = new LatLng(lat, lon);
					// aMap.moveCamera(CameraUpdateFactory.changeLatLng(point1));
					aMap.clear();
					aMap.moveCamera(CameraUpdateFactory.zoomTo(18));
				}
			});
		} else {
			aMap.clear();
			final double lat = bundle.getDouble("lat");
			final double lon = bundle.getDouble("lon");
			if (type == 7) {
				Marker myMarker = aMap.addMarker(new MarkerOptions()
						.anchor(0.5f, 0.5f)
						.position(new LatLng(lat, lon))
						.snippet("头像")
						// .icon(BitmapDescriptorFactory.fromView(view))
						.icon(BitmapDescriptorFactory
								.fromResource(R.drawable.amap_point))
						.draggable(true).period(50));
				myMarker.showInfoWindow();
			}
			aMap.setLocationSource(this);// 设置定位监听
			aMap.setMyLocationStyle(new MyLocationStyle()
					.myLocationIcon(BitmapDescriptorFactory
							.fromResource(getArguments().getInt("icon"))));
			aMap.setOnMapLoadedListener(new OnMapLoadedListener() {

				@Override
				public void onMapLoaded() {
					// TODO Auto-generated method stub
					LatLng point1 = new LatLng(lat, lon);
					aMap.moveCamera(CameraUpdateFactory.changeLatLng(point1));
					aMap.moveCamera(CameraUpdateFactory.zoomTo(18));
				}
			});
		}

	}
	private void selectAddress() {
		aMap.setOnCameraChangeListener(new OnCameraChangeListener() {
			
			@Override
			public void onCameraChangeFinish(CameraPosition cameraPosition) {
				// TODO Auto-generated method stub
				LatLonPoint point = AMapUtil
						.convertToLatLonPoint(cameraPosition.target);
				centerLat = cameraPosition.target.latitude;
				centerLon = cameraPosition.target.longitude;
				doSearchAddress(point);
			}
			
			@Override
			public void onCameraChange(CameraPosition arg0) {
				// TODO Auto-generated method stub
				
			}
		});
		aMap.getUiSettings().setZoomControlsEnabled(false);
		

			dingweiRL.setVisibility(View.VISIBLE);
			aMap.setLocationSource(this);// 设置定位监听
			// aMap.getUiSettings().setMyLocationButtonEnabled(true); //
			// 是否显示默认的定位按钮
			// aMap.setMyLocationEnabled(true);// 是否可触发定位并显示定位层
		
	
	
		// aMap.getUiSettings().setMyLocationButtonEnabled(true); //
		// 是否显示默认的定位按钮
		// aMap.setMyLocationEnabled(true);// 是否可触发定位并显示定位层
//		aMap.setMyLocationStyle(new MyLocationStyle()
//		.myLocationIcon(BitmapDescriptorFactory
//				.fromResource(getArguments().getInt("icon"))));
		Bundle bundle = getArguments();
		if (bundle.getDouble("lat") == 0.0 && bundle.getDouble("lon") == 0.0) {
			if (aMapManager == null) {
				aMapManager = LocationManagerProxy
						.getInstance(getActivity());
			}
			aMapManager.requestLocationData(
					LocationProviderProxy.AMapNetwork, -1, 100,
					AMapFrg.this);
			aMap.setOnMapLoadedListener(new OnMapLoadedListener() {
				
				@Override
				public void onMapLoaded() {
					aMap.clear();
					aMap.moveCamera(CameraUpdateFactory.zoomTo(16));
				}
			});
		}else{
			aMap.clear();
			final double lat = bundle.getDouble("lat");
			final double lon = bundle.getDouble("lon");
			aMap.setOnMapLoadedListener(new OnMapLoadedListener() {

				@Override
				public void onMapLoaded() {
					// TODO Auto-generated method stub
					LatLng point1 = new LatLng(lat, lon);
					aMap.moveCamera(CameraUpdateFactory.changeLatLng(point1));
					aMap.moveCamera(CameraUpdateFactory.zoomTo(16));
				}
			});
		}
		
		
	
		
	}

	private void drawRoute(Bundle bundle) {
		LatLng startLatLng = new LatLng(bundle.getDouble("startLat"),
				bundle.getDouble("startLon"));
		LatLng endLatLng = new LatLng(bundle.getDouble("endLat"),
				bundle.getDouble("endLon"));
		startPoint = new LatLonPoint(startLatLng.latitude,
				startLatLng.longitude);
		endPoint = new LatLonPoint(endLatLng.latitude, endLatLng.longitude);

		final RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(
				startPoint, endPoint);
		// 驾车路径规划
		DriveRouteQuery query = new DriveRouteQuery(fromAndTo,
				RouteSearch.DrivingDefault, null, null, "");// 第一个参数表示路径规划的起点和终点，第二个参数表示驾车模式，第三个参数表示途经点，第四个参数表示避让区域，第五个参数表示避让道路
		routeSearch.calculateDriveRouteAsyn(query);// 异步路径规划驾车模式查询
	}

	private void drawNav() {
		aMap.clear();
		Bundle bundle = getArguments();
		navEndLat = bundle.getDouble("endLat");
		navEndLon = bundle.getDouble("endLon");

		String content = bundle.getString("content");
		Marker myMarker = aMap.addMarker(new MarkerOptions().anchor(0.5f, 0.5f)
				.position(new LatLng(navEndLat, navEndLon)).snippet("位置")
				// .icon(BitmapDescriptorFactory.fromResource(R.drawable.start))
				.draggable(true).period(50));
		myMarker.showInfoWindow();
		aMap.setOnMapLoadedListener(new OnMapLoadedListener() {

			@Override
			public void onMapLoaded() {
				// TODO Auto-generated method stub
				LatLng point1 = new LatLng(navEndLat, navEndLon);
				aMap.moveCamera(CameraUpdateFactory.changeLatLng(point1));
				aMap.moveCamera(CameraUpdateFactory.zoomTo(18));
			}
		});
	}

	private void drawNavCarAndDriver() {
		aMap.clear();
		Bundle bundle = getArguments();
		navEndLat = bundle.getDouble("endLat");
		navEndLon = bundle.getDouble("endLon");
		String content = bundle.getString("content");
		String[] contentArray = bundle.getStringArray("contentArray");
		int type = bundle.getInt("type");
		BitmapDescriptor bit = null;

		try {
			if (contentArray.length == 2) {
				bit = BitmapDescriptorFactory.fromResource(R.drawable.amap_car);
			} else {
				bit = BitmapDescriptorFactory
						.fromResource(R.drawable.amap_driver);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			bit = BitmapDescriptorFactory.defaultMarker();
		}

		Marker myMarker = aMap.addMarker(new MarkerOptions().anchor(0.5f, 0.5f)
				.position(new LatLng(navEndLat, navEndLon)).snippet("位置")
				.icon(bit)
				// .icon(BitmapDescriptorFactory.fromResource(R.drawable.start))
				.draggable(true).period(50));
		myMarker.showInfoWindow();
		aMap.setOnMapLoadedListener(new OnMapLoadedListener() {

			@Override
			public void onMapLoaded() {
				// TODO Auto-generated method stub
				LatLng point1 = new LatLng(navEndLat, navEndLon);
				aMap.moveCamera(CameraUpdateFactory.changeLatLng(point1));
				aMap.moveCamera(CameraUpdateFactory.zoomTo(18));
			}
		});
	}

	/**
	 * 初始化AMap对象
	 */
	private void init() {
		if (aMap == null) {
			aMap = mapView.getMap();
			registerListener();
		}
//		aMap.getUiSettings().setRotateGesturesEnabled(false);
//		aMap.getUiSettings().setTiltGesturesEnabled(false);
		routeSearch = new RouteSearch(getActivity());
		routeSearch.setRouteSearchListener(this);

	}

	public AMap getAmap() {
		return mapView.getMap();
	}

	/**
	 * 注册监听
	 */
	private void registerListener() {
		aMap.setOnMapClickListener(AMapFrg.this);
		aMap.setOnMarkerClickListener(AMapFrg.this);
		aMap.setOnInfoWindowClickListener(AMapFrg.this);
		aMap.setInfoWindowAdapter(AMapFrg.this);
	}

	/**
	 * 隐藏进度框
	 */
	private void dissmissProgressDialog() {
		DisMissLoadingDiaEvent dia = new DisMissLoadingDiaEvent();
		dia.isToShow = false;
		BusProvider.getInstance().post(dia);
	}

	@Override
	public void onBusRouteSearched(BusRouteResult arg0, int arg1) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onDriveRouteSearched(DriveRouteResult result, int rCode) {
		// TODO Auto-generated method stub
		dissmissProgressDialog();
		if (rCode == 0) {
			if (result != null && result.getPaths() != null
					&& result.getPaths().size() > 0) {
				driveRouteResult = result;
				DrivePath drivePath = driveRouteResult.getPaths().get(0);
				aMap.clear();// 清理地图上的所有覆盖物
				DrivingRouteOverlay drivingRouteOverlay = new DrivingRouteOverlay(
						getActivity(), aMap, drivePath,
						driveRouteResult.getStartPos(),
						driveRouteResult.getTargetPos());
				
				drivingRouteOverlay.removeFromMap();
				drivingRouteOverlay.addToMap();
				drivingRouteOverlay.removeStation();
				drivingRouteOverlay.zoomToSpan();
			} else {
				Toast.makeText(getActivity(), "对不起，没有搜索到相关数据！", 1).show();
			}
		} else if (rCode == 27) {
			Toast.makeText(getActivity(), "搜索失败,请检查网络连接！", 1).show();
		} else if (rCode == 32) {
			Toast.makeText(getActivity(), "key验证无效！", 1).show();
		} else {
			Toast.makeText(getActivity(), "未知错误，请稍后重试!错误码为" + rCode, 1).show();
		}
	}

	/**
	 * 开始进行poi搜索
	 */
	protected void doSearchQuery(LatLonPoint lp) {
		if(getActivity()==null || isDetached()){
			return;
		}
		// showProgressDialog();// 显示进度框
		currentPage = 0;
		aMap.setOnMapClickListener(null);// 进行poi搜索时清除掉地图点击事件

		String queryType = getArguments().getString("queryType");// "餐饮|酒店|4s|停车场|住宿|导航|汽车修理|百货|物流园|洗车|快餐 "
		if (queryType == null || queryType.equals("")) {
			queryType = "加油站|物流中心|物流园|物流圈|轮胎|停车场|餐饮|酒店|4s|住宿|导航|汽车修理|百货|洗车|快餐|机油|篷布";
		}
		query = new PoiSearch.Query("",queryType , "");// 第一个参数表示搜索字符串，第二个参数表示poi搜索类型，第三个参数表示poi搜索区域（空字符串代表全国）
		query.setPageSize(10);// 设置每页最多返回多少条poiitem
		query.setPageNum(currentPage);
		poiSearch = null;

		if (lp != null) {
			poiSearch = new PoiSearch(getActivity(), query);
			poiSearch.setOnPoiSearchListener(this);
			poiSearch.setBound(new SearchBound(lp, 10000, true));//
			poiSearch.searchPOIAsyn();// 异步搜索
			
			
		}
	}
	
	

	protected void doSearchAddress(final LatLonPoint lp) {
		
		GeocodeSearch geocoderSearch = new GeocodeSearch(getActivity()); 

		geocoderSearch.setOnGeocodeSearchListener(new OnGeocodeSearchListener() {
			
			@Override
			public void onRegeocodeSearched(RegeocodeResult result, int rCode) {
				// TODO Auto-generated method stub
				  if(rCode == 0){ 
				      
				        if(result != null&&result.getRegeocodeAddress() != null 
				                 ){ 

				        	RegeocodeAddressEvent event = new RegeocodeAddressEvent();
				        	event.address = result.getRegeocodeAddress();
							event.lat = centerLat;
							event.lon = centerLon;
				            BusProvider.getInstance().post(event);
				            
				            doSearchQuery(lp);
				            
				           // Toast.makeText(getActivity(), addressName, Toast.LENGTH_LONG).show(); 
				        }else{ 
				            //ToastUtil.show(GeocoderActivity.this, R.string.no_result); 
				        } 
				    }else{ 
				        //ToastUtil.show(GeocoderActivity.this, R.string.error_network); 
				    }
				     
			}
			
			@Override
			public void onGeocodeSearched(GeocodeResult result, int rCode) {

				// TODO Auto-generated method stub
				
			}
		}); 	

		// 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标
		RegeocodeQuery query = new RegeocodeQuery(lp, 20000,GeocodeSearch.AMAP);
	
		geocoderSearch.getFromLocationAsyn(query);
	}

	
	
	/**
	 * poi搜索更多
	 */
	public void nextSearch() {
		if (query != null && poiSearch != null && poiResult != null) {
			if (poiResult.getPageCount() - 1 > currentPage) {
				currentPage++;

				query.setPageNum(currentPage);// 设置查后一页
				poiSearch.searchPOIAsyn();
			} else {
				Toast.makeText(getActivity(), "没有更多数据了", 2).show();
				postNull();
			}
		} else {
			postNull();
		}
	}

	private void postNull() {

		new Handler().postDelayed(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				PoiListEvent event = new PoiListEvent();
				event.lat = centerLat;
				event.lon = centerLon;
				event.isNull = true;
				BusProvider.getInstance().post(event);
			}
		}, 1000);

	}

	@Override
	public void onWalkRouteSearched(WalkRouteResult arg0, int arg1) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onPoiItemDetailSearched(PoiItemDetail arg0, int arg1) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onPoiSearched(PoiResult result, int rCode) {
		// TODO Auto-generated method stub
		if (getActivity() == null || isDetached()) {
			return;
		}
		dissmissProgressDialog();// 隐藏对话框
		List<PoiItem> poiItems;
		if (rCode == 0) {
			if (result != null && result.getQuery() != null) {// 搜索poi的结果
				if (result.getQuery().equals(query)) {// 是否是同一条
					poiResult = result;
					poiItems = poiResult.getPois();// 取得第一页的poiitem数据，页数从数字0开始
					if (poiItems != null && poiItems.size() > 0) {
						// aMap.clear();// 清理之前的图标
						PoiListEvent event = new PoiListEvent();
						event.lat = centerLat;
						event.lon = centerLon;
						event.poiList = poiItems;
						event.isMore = currentPage == 0 ? false : true;
						BusProvider.getInstance().post(event);
					} else {
						// 周边没有相关点
						PoiListEvent event = new PoiListEvent();
						event.lat = centerLat;
						event.lon = centerLon;
						event.isMore = currentPage == 0 ? false : true;
						event.isNull = true;
						BusProvider.getInstance().post(event);
					}
				}
			} else {
				// 周边没有相关点
				postNull();
			}
		} else if (rCode == 27) {
			Toast.makeText(getActivity(), "搜索失败,请检查网络连接！", 1).show();
			postNull();
		} else if (rCode == 32) {
			Toast.makeText(getActivity(), "key验证无效！", 1).show();
		} else {
			Toast.makeText(getActivity(), "未知错误，请稍后重试!错误码为" + rCode, 1).show();
		}
	}

	@Override
	public View getInfoContents(Marker arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public View getInfoWindow(Marker arg0) {
		// TODO Auto-generated method stub
		if (type == 4) {
			String content = getArguments().getString("content");

			View infoWindow = getActivity().getLayoutInflater().inflate(
					R.layout.amap_view_info_window, null);

			TextView titleView = (TextView) infoWindow.findViewById(R.id.title);
			titleView.setText(content);

			infoWindow.findViewById(R.id.goNavRL).setOnClickListener(
					new OnClickListener() {

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub

							SharedPreferences sp = getActivity()
									.getSharedPreferences("NAVI",
											Context.MODE_PRIVATE);
							String defaultPkgName = sp.getString("NAVI", "");
							if (TextUtils.isEmpty(defaultPkgName)) {
								showNavPop();
							} else {
								ChoiceNaviPopView.toNav(getActivity(),
										navEndLat, navEndLon, defaultPkgName);
							}
						}
					});

			return infoWindow;

		} else if (type == 6) {
			BaseVolley.getRequestQueue(getActivity());
			final String url = getArguments().getString("url");
			View view = getActivity().getLayoutInflater().inflate(
					R.layout.amap_view_touxiang_info_window, null);
			RoundedImageView img = (RoundedImageView) view
					.findViewById(R.id.touxiang);
			if (TextUtils.isEmpty(url)) {
				img.setImageResource(R.drawable.amap_dispatch_logo);
			} else {
				BaseVolley.getImageLoader(getActivity()).get(
						Rop.getSmallUrl(getActivity(), url),
						ImageLoader.getImageListener(img,
								R.drawable.amap_dispatch_logo,
								R.drawable.amap_dispatch_logo),DimenTool.dip2px(getActivity(), 90),DimenTool.dip2px(getActivity(), 90));
			}
			
			return view;

			// String content = "dasdasd";
			//
			//
			// View infoWindow = getActivity().getLayoutInflater().inflate(
			// R.layout.amap_view_info_window, null);
			//
			// TextView titleView =
			// (TextView)infoWindow.findViewById(R.id.title);
			// titleView.setText(content);
			//
			// infoWindow.findViewById(R.id.goNavRL).setOnClickListener(new
			// OnClickListener() {
			//
			// @Override
			// public void onClick(View v) {
			// // TODO Auto-generated method stub
			//
			// SharedPreferences sp = getActivity().getSharedPreferences("NAVI",
			// getActivity().MODE_PRIVATE);
			// String defaultPkgName = sp.getString("NAVI", "");
			// if(TextUtils.isEmpty(defaultPkgName)){
			// showNavPop();
			// }else{
			// ChoiceNaviPopView.toNav(getActivity(), navEndLat, navEndLon,
			// defaultPkgName);
			// }
			// }
			// });
			//
			// return infoWindow;
		} else if (type == 2) {
			return null;
		} else if (type == 7) {
			BaseVolley.getRequestQueue(getActivity());
			final String url = getArguments().getString("url");
			View view = getActivity().getLayoutInflater().inflate(
					R.layout.amap_view_touxiang_info_window, null);
			RoundedImageView img = (RoundedImageView) view
					.findViewById(R.id.touxiang);
			BaseVolley.getImageLoader(getActivity()).get(
					Rop.getSmallUrl(getActivity(), url),
					ImageLoader.getImageListener(img,
							R.drawable.amap_dispatch_logo,
							R.drawable.amap_dispatch_logo),DimenTool.dip2px(getActivity(), 90),DimenTool.dip2px(getActivity(), 90));
			return view;
		} else if (type == 8 || type == 9 || type == 10) {
			String[] contentArray = getArguments().getStringArray(
					"contentArray");

			View infoWindow = getActivity().getLayoutInflater().inflate(
					R.layout.amap_view_info_window, null);

			TextView titleView = (TextView) infoWindow.findViewById(R.id.title);
			TextView titleView2 = (TextView) infoWindow
					.findViewById(R.id.title2);
			TextView titleView3 = (TextView) infoWindow
					.findViewById(R.id.title3);
			int count = contentArray.length;
			if (count == 1) {
				titleView.setVisibility(View.VISIBLE);
				titleView.setText(contentArray[0]);
				titleView2.setVisibility(View.GONE);
				titleView3.setVisibility(View.GONE);
			} else if (count == 2) {
				titleView.setVisibility(View.VISIBLE);
				titleView2.setVisibility(View.VISIBLE);
				titleView3.setVisibility(View.GONE);

				titleView.setText(contentArray[0]);
				titleView2.setText(contentArray[1]);
			} else if (count == 3) {
				titleView.setVisibility(View.VISIBLE);
				titleView2.setVisibility(View.VISIBLE);
				titleView3.setVisibility(View.VISIBLE);

				titleView.setText(contentArray[0]);
				titleView2.setText(contentArray[1]);
				titleView3.setText(contentArray[2]);
			}

			infoWindow.findViewById(R.id.goNavRL).setOnClickListener(
					new OnClickListener() {

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub

							SharedPreferences sp = getActivity()
									.getSharedPreferences("NAVI",
											Context.MODE_PRIVATE);
							String defaultPkgName = sp.getString("NAVI", "");
							if (TextUtils.isEmpty(defaultPkgName)) {
								showNavPop();
							} else {
								ChoiceNaviPopView.toNav(getActivity(),
										navEndLat, navEndLon, defaultPkgName);
							}
						}
					});

			return infoWindow;

		} else {
			return null;
		}

	}

	@Override
	public void onInfoWindowClick(Marker arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onMapClick(LatLng arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onMarkerClick(Marker arg0) {
		// TODO Auto-generated method stub
		if (arg0.isInfoWindowShown()) {
			arg0.hideInfoWindow();
		} else {
			arg0.showInfoWindow();
		}
		return false;
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		BusProvider.getInstance().register(this);
		mapView.onResume();
	}

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		BusProvider.getInstance().unregister(this);
		mapView.onPause();
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		// TODO Auto-generated method stub
		super.onSaveInstanceState(outState);
		mapView.onSaveInstanceState(outState);
	}

	@Override
	public void onDestroyView() {
		// TODO Auto-generated method stub
		super.onDestroyView();
		mapView.onDestroy();
	}

	@Override
	public void onCameraChange(CameraPosition arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onCameraChangeFinish(CameraPosition cameraPosition) {
		// TODO Auto-generated method stub
		LatLonPoint point = AMapUtil
				.convertToLatLonPoint(cameraPosition.target);
		centerLat = cameraPosition.target.latitude;
		centerLon = cameraPosition.target.longitude;
		doSearchQuery(point);
	}

	public static class PoiListEvent {
		public double lat;
		public double lon;
		public List<PoiItem> poiList;
		public boolean isMore;
		public boolean isNull;
	}
	public static class RegeocodeAddressEvent {
		public double lat;
		public double lon;
		public RegeocodeAddress address;

	}
	


	public static class DisMissLoadingDiaEvent {
		public boolean isToShow;
	}

	@Override
	public void activate(OnLocationChangedListener listener) {
		// TODO Auto-generated method stub
		mListener = listener;
		if (aMapManager == null) {
			aMapManager = LocationManagerProxy.getInstance(getActivity());
		}
		/**
		 * provider：有三种定位Provider供用户选择，分别是:LocationManagerProxy.GPS_PROVIDER，代表使用手机GPS定位；LocationManagerProxy.NETWORK_PROVIDER，代表使用手机网络定位；LocationProviderProxy.AMapNetwork，代表高德网络定位服务，混合定位。
			minTime：位置变化的通知时间，单位为毫秒。如果为-1，定位只定位一次。
			minDistance:位置变化通知距离，单位为米。
			listener:定位监听者。
		 */
		aMapManager.requestLocationData(LocationProviderProxy.AMapNetwork, -1, 2000, this);
	}

	@Override
	public void deactivate() {
		// TODO Auto-generated method stub
		mListener = null;
		if (aMapManager != null) {
			aMapManager.removeUpdates(this);
			aMapManager.destory();
		}
		aMapManager = null;
	}

	@Override
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onLocationChanged(AMapLocation arg0) {
		// TODO Auto-generated method stub
		
		myLat = arg0.getLatitude();
		myLon = arg0.getLongitude();
		
		if (getArguments().getInt("type") == 2 || getArguments().getInt("type") == 11) {
			LatLng point1 = new LatLng(arg0.getLatitude(), arg0.getLongitude());
			aMap.moveCamera(CameraUpdateFactory.changeLatLng(point1));
			aMap.moveCamera(CameraUpdateFactory.zoomTo(18));
			aMap.clear();
		} else if (mListener != null) {
			// if(getArguments().getInt("type") == 2){
			// LatLng point1 = new LatLng(arg0.getLatitude(),
			// arg0.getLongitude());
			// aMap.moveCamera(CameraUpdateFactory.changeLatLng(point1));
			// aMap.moveCamera(CameraUpdateFactory.zoomTo(18));
			// }else{
			mListener.onLocationChanged(arg0);// 显示系统小蓝点
			if (getArguments().getInt("type") == 2) {
				aMap.clear();
			}

			// }

		}
	}

	private String[] pkgList = new String[] { "com.baidu.BaiduMap",
			"com.autonavi.minimap" };
	private PackageManager pm;

	private List<NaviBean> getNaviList() {
		List<NaviBean> list = new ArrayList<NaviBean>();
		pm = getActivity().getPackageManager();
		for (int i = 0; i < pkgList.length; i++) {
			ApplicationInfo appInfo = null;
			try {
				appInfo = pm.getApplicationInfo(pkgList[i], 0);
			} catch (NameNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (appInfo != null) {
				NaviBean bean = new NaviBean();
				bean.icon = pm.getApplicationIcon(appInfo);
				bean.name = (String) pm.getApplicationLabel(appInfo);
				bean.pkgName = pkgList[i];
				list.add(bean);
			}
		}
		return list;
	}

	private void showNavPop() {
		List<NaviBean> list = getNaviList();
		ChoiceNaviPopView view = new ChoiceNaviPopView(getActivity(), list,
				navEndLat, navEndLon);
		pop = new PopupWindow(view, LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT, true);
		ColorDrawable dw = new ColorDrawable(-00000);
		pop.setBackgroundDrawable(dw);
		view.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				pop.dismiss();
			}
		});
		pop.showAtLocation(view, Gravity.CENTER, 0, 0);
	}

	@Subscribe
	public void ReShowPop(
			com.sijibao.amap.frg.ChoiceNaviPopView.ReShowPopEvent event) {
		showNavPop();
	}

	@Subscribe
	public void closePop(ClosePopEvent event) {
		if (pop != null) {
			pop.dismiss();
		}
	}

	public double getCenterPointLat() {
		return centerLat;
	}

	public double getCenterPointLon() {
		return centerLon;
	}
}
